package com.homedo.microservice.open.service.gateway.manager.web.util;

import com.google.common.collect.Lists;
import com.homedo.common.bean.data.enums.ResponseEnum;
import com.homedo.common.bean.vo.context.UserContext;
import com.homedo.common.bean.vo.context.UserVo;
import com.homedo.common.exception.UserContextException;
import com.homedo.common.util.Detect;
import com.homedo.common.util.support.UserContextHolder;
import com.homedo.microservice.open.service.gateway.manager.web.bean.constant.RoleConstant;
import com.homedo.microservice.open.service.gateway.manager.web.cas.model.UserInfo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

//import com.homedo.screwdriver.bean.constant.RoleConstant;
//import com.homedo.screwdriver.cas.model.UserInfo;

public class UserContextUtil {
    public static UserContext getUserContext() {
        UserContext userContext = UserContextHolder.getUserContext();
        if (userContext != null) {
            return userContext;
        }

//        Object userInfoObj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();


        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();


        SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession()
                .getAttribute("SPRING_SECURITY_CONTEXT");

        if (securityContextImpl == null) {
            throw new UserContextException(ResponseEnum.NOT_LOGIN);
        }

        Authentication authentication = securityContextImpl.getAuthentication();
        if (authentication == null) {
            throw new UserContextException(ResponseEnum.NOT_LOGIN);
        }

        Object userInfoObj = authentication.getPrincipal();

//        // 登录名
//        System.out.println("Username:" + securityContextImpl.getAuthentication().getName());
//        // 登录密码，未加密的
//        System.out.println("Credentials:" + securityContextImpl.getAuthentication().getCredentials());
//        WebAuthenticationDetails details = (WebAuthenticationDetails) securityContextImpl.getAuthentication()
//                .getDetails();
//        // 获得访问地址
//        System.out.println("RemoteAddress" + details.getRemoteAddress());
//        // 获得sessionid
//        System.out.println("SessionId" + details.getSessionId());
//        // 获得当前用户所拥有的权限
//        List<GrantedAuthority> authorities = (List<GrantedAuthority>) securityContextImpl.getAuthentication()
//                .getAuthorities();
//        for (GrantedAuthority grantedAuthority : authorities) {
//            System.out.println("Authority" + grantedAuthority.getAuthority());
//        }
//

        if (userInfoObj == null || !(userInfoObj instanceof UserInfo)) {
            throw new UserContextException(ResponseEnum.NOT_LOGIN);
        }
        UserInfo userInfo = (UserInfo) userInfoObj;

        userContext = new UserContext();
        userContext.setUsername(userInfo.getUsername());
        UserVo userVo = new UserVo();
        userVo.setAccountName(userInfo.getUsername());
        userContext.setUser(userVo);

        List<String> roles = Lists.newArrayList();
        List<String> resources = Lists.newArrayList();
        if (Detect.notEmpty(userInfo.getAuthorities())) {
            userInfo.getAuthorities().forEach(e -> {
                if (!e.getAuthority().equals(RoleConstant.ROLE_EXTRAL_USER_RESOURCE)) {
                    roles.add(e.getAuthority());
                }

                if (Detect.notEmpty(e.getResources())) {
                    resources.addAll(e.getResources());
                }
            });
        }
        
        userContext.setRoles(roles);
        userContext.setResources(resources);


        UserContextHolder.setUsercontext(userContext);

        return userContext;
    }

}
